using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Entities;

namespace DAL
{
    public class tbDanhmucDAL
    {
        private SqlConnection cn = null;
        public tbDanhmucDAL()
        {
            cn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConnection"].ConnectionString);
            cn.Open();
        }
        public void Insert(tbDanhmuc dm)
        {
            SqlCommand cm = new SqlCommand("Danh_muc_Insert", cn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@tendanhm", dm.Tendanhm);
            cm.ExecuteNonQuery();
        }
        public void Update(tbDanhmuc dm)
        {
            SqlCommand cm = new SqlCommand("Danh_muc_Update", cn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@madanhm", dm.Madanhm);
            cm.Parameters.AddWithValue("@tendanhm", dm.Tendanhm);
            cm.ExecuteNonQuery();
        }
        public void Delete(int iD)
        {
            SqlCommand cm = new SqlCommand("Danh_muc_Delete", cn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@madanhm", iD);
            cm.ExecuteNonQuery();
        }
        public tbDanhmucCollection Get(string where, int pageIndex, int pageSize, string orderBy, string orderDirection, out int totalRecords)
        {
            SqlCommand cm = new SqlCommand("Danh_muc_Get", cn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@Where", where);
            cm.Parameters.AddWithValue("@PageIndex", pageIndex);
            cm.Parameters.AddWithValue("@PageSize", pageSize);
            cm.Parameters.AddWithValue("@OrderBy", orderBy);
            cm.Parameters.AddWithValue("@OrderDirection", orderDirection);
            cm.Parameters.Add(new SqlParameter("@TotalRecords", DbType.Int32)).Direction = ParameterDirection.Output;

            SqlDataReader dr = cm.ExecuteReader();
            tbDanhmucCollection tbdanhmucCollection = new tbDanhmucCollection();

            while (dr.Read()) 
            {
                tbDanhmuc tbdanhmuc = new tbDanhmuc();
                tbdanhmuc.Madanhm = int.Parse(dr.GetValue(0).ToString());
                tbdanhmuc.Tendanhm = dr.GetValue(1).ToString();
                tbdanhmucCollection.Add(tbdanhmuc);
            }
            dr.Close();
            totalRecords = int.Parse(cm.Parameters["@TotalRecords"].Value.ToString());
            return tbdanhmucCollection;
        }
    }
}
